<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class Admin_Form_Privilege_Privileges extends RedCross_Form
{

    public function init()
    {
        $this->setAttrib('id', 'privileges_privileges');

        $this->addElement('submit', 'submit', array(
            'required' => true,
            'ignore'   => true,
            'order'    => 1000,
            'label'    => 'Lagre endringer',
        ));
    }

    public function fillForm($resources)
    {
        foreach ($resources as $resource) {
            $elementName = $this->_addResourceElement($resource->id);
            $this->_formatResourceName($elementName, $resource->name);

            // Add the options
            foreach ($resource->Privileges as $privilege) {
            	$this->getElement($elementName)->addMultiOption($privilege->id, ucfirst($privilege->name));
            }
        }
    }

    private function _addResourceElement($resourceId)
    {
        $name = 'resource_' . $resourceId;
        $this->addElement('multiCheckbox', $name, array('separator' => ' | '));
        $this->getElement($name)->setDecorators(array(
            array('ViewHelper'),
                array('Errors'),
                array('Description', array('placement' => Zend_Form_Decorator_Abstract::PREPEND, 'class' => 'test')),
                array('HtmlTag', array('tag' => 'li'))
        ));
        return $name;
    }

    private function _formatResourceName($elementName, $resourceName)
    {
        // Format the name of the resource to a more human readable format 
        $array = explode(':', $resourceName);
        $resourceType = ucfirst($array[0]);
        $array = explode('.', $array[1]);
        $resourceModule = count($array) == 2 ? (ucfirst(array_shift($array)) . ' - ') : '';
        $resourceAction = ucfirst($array[0]);
        unset($array);
        $this->getElement($elementName)->setDescription($resourceType . ': ' . $resourceModule . $resourceAction);
    }

    public function populateForm($privileges)
    {
        $array = array();
        foreach ($privileges as $p) {
            $array[$p->Resource->id][] = $p->id;
        }

        foreach ($array as $r => $p) {
            $this->getElement('resource_' . $r)->setValue($p);
        }
    }
}
